package com.sh.caryr.erp.controller.user;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.sh.caryr.erp.entity.PageResultMessage;
import com.sh.caryr.erp.entity.ResultMessage;
import com.sh.caryr.erp.custmz.UserAuthorityContainer;
import com.sh.caryr.erp.exception.ResultCode;
import com.sh.caryr.erp.entity.user.User;
import com.sh.caryr.erp.entity.user.UserRole;
import com.sh.caryr.erp.exception.RestServiceException;
import com.sh.caryr.erp.service.IUserService;
import com.sh.caryr.erp.util.ERPConstants;
import com.sh.caryr.erp.util.MyBatisUtil;
import com.sh.caryr.erp.util.UtilityTool;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author milkeeper
 * @since 2017-11-22
 */
@RestController
@RequestMapping("/api/user")
@SessionAttributes("user")
public class UserController {
    @Autowired
    private IUserService userService;

    @ApiOperation(value = "用户登陆", notes = "用户登陆")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ModelAttribute("user")
    public void login(Model model, User user,HttpSession httpSession) {
        user = login(user);
        if (user != null) {
            model.addAttribute("user", user);
            if (httpSession.getAttribute("lang") == null) {
                httpSession.setAttribute("lang", ERPConstants.LANG_CN);
            }

            String authStr = UserAuthorityContainer.convertUserAuthToString(user);
            boolean isSuperUser = ERPConstants.SYS_SUPER_USERNAME.equals(user.getName()) || user.getIsSuperuser() == ERPConstants.ENITYT_ACTIVE ? true : false;
            httpSession.setAttribute("authStr", authStr);
            httpSession.setAttribute("isSuperUser", isSuperUser);
        } else {
            throw new RestServiceException(HttpStatus.NOT_FOUND, ResultCode.ENTITY_NOT_FOUND);
        }
    }

    @ApiOperation(value = "用户退出", notes = "用户退出")
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public void logout(SessionStatus status) {
        status.setComplete(); //Remove attributes from session
    }

    @ApiOperation(value = "获取用户列表信息", notes = "获取用户列表信息")
    @RequestMapping(method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public ResultMessage<List<User>> findUsers(@RequestParam(defaultValue = "1") Integer current,
                                               @RequestParam(defaultValue = "20") Integer size,
                                               @RequestParam(required = false) String queryField,
                                               @RequestParam(required = false) String queryValue,
                                               @RequestParam(required = false) Boolean isAccurate,
                                               @RequestParam(defaultValue = "id") String orderBy,
                                               @RequestParam(defaultValue = "false") Boolean isAsc,
                                               @ModelAttribute("user") User operator) {
        Wrapper wrapper = MyBatisUtil.getIsActiveWrapper(queryField, queryValue, orderBy,isAsc);
        MyBatisUtil.addAuthFilter(wrapper,operator,ERPConstants.AUTH_TARGET_USER,false,true);
        List<User> users = userService.findUsersDynamic(current, size, wrapper, orderBy);
        return new PageResultMessage<>(users, userService.selectCount(wrapper));
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public User findUserById(@PathVariable long id) {
        User user = userService.selectById(id);
        if (user == null) {
            throw new RestServiceException(HttpStatus.NOT_FOUND, ResultCode.ENTITY_NOT_FOUND);
        }
        return user;
    }

    @ApiOperation(value = "创建User", notes = "创建User")
    @ApiImplicitParam(name = "user", value = "详细实体user", required = true, dataType = "User")
    @RequestMapping(method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    public Object insertUser(@RequestBody User user, @ModelAttribute("user") User operator) {
        user.setCreateBy(operator.getId());
        user.setCoco(operator.getCoco());
        if (!userService.insert(user)) {
            new RestServiceException(ResultCode.CREATE_FAILED);
        }
        return new ResultMessage<>(user.getId().toString());
    }

    @ApiOperation(value = "更新", notes = "更新")
    @ApiImplicitParam(name = "user", value = "实体", required = true, dataType = "User")
    @RequestMapping(method = RequestMethod.PUT)
    @ResponseStatus(HttpStatus.OK)
    public Object updateUserById(@RequestBody User user, @ModelAttribute("user") User operator) {
        user.setUpdateBy(operator.getId());
        user.setUpdateAt(new Date());
        if (!userService.updateById(user)) {
            throw new RestServiceException(ResultCode.UPDATE_FAILED);
        }
        return new ResultMessage<>(user);
    }

    @ApiOperation(value = "批量User", notes = "根据url的id来指定删除对象")
    @ApiImplicitParam(name = "ids", value = "UserRole IDS", required = true, dataType = "String")
    @RequestMapping(value = "/{ids}", method = RequestMethod.DELETE)
    @ResponseStatus(HttpStatus.OK)
    public ResultMessage deleteUserById(@PathVariable String ids) {
        List<Long> list = UtilityTool.convertStringArray2LongList(ids.split(","));
        try {
            UtilityTool.softDelete(User.class,list, userService);
            return new ResultMessage();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RestServiceException(ResultCode.DELETE_NOT_FOUND);
        }

    }

    /**
     * 软删除，isActive = 0
     *
     * @param list
     */
    private void softDelete(List<Long> list) {
        List<User> users = userService.selectBatchIds(list);
        for (User user : users) {
            user.setIsActive(ERPConstants.ENITYT_INACTIVE);
        }
        if (!userService.updateBatchById(users)) {
            throw new RestServiceException(ResultCode.UPDATE_FAILED);
        }
    }

    private User login(User user) {
        // Administrator
        if (ERPConstants.SYS_SUPER_USERNAME.equals(user.getName()) && ERPConstants.SYS_SUPER_USERNAME.equals(user.getPassword())) {
            //超级管理员id 888888
            user.setId(888888L);
            UserRole role = new UserRole();
            role.setAuthList(UserAuthorityContainer.allAuthsData().getData());
            user.setUserRole(role);
            return user;
        }

        if (user == null || user.getName() == null || "".equals(user.getName()) || user.getPassword() == null
                || "".equals(user.getPassword())) {
            throw new RestServiceException(HttpStatus.NOT_FOUND, ResultCode.ENTITY_NOT_FOUND);
        } else {
            Wrapper<User> wrapper = new EntityWrapper<User>().eq("coco", user.getCoco());
            wrapper.eq("name", user.getName());
            List<User> dbUsers = userService.findUsersDynamic(wrapper);
            if (dbUsers == null || dbUsers.size() == 0) {
                throw new RestServiceException(HttpStatus.NOT_FOUND, ResultCode.ENTITY_NOT_FOUND);
            }
            User dbUser = dbUsers.get(0);
            if (!user.getPassword().equals(dbUser.getPassword())) {
                throw new RestServiceException(ResultCode.PWD_INCORRECT);
            }
            return dbUser;
        }
    }

}
